<template>
  <div>
    <el-card class="search-card">
      <basic-form
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="clearCategorySelect"
        @getFormData="getFormData"
      >
        <CategoryMultipleSelect
          slot="category"
          ref="categoryMultiple"
          @selectCategoryCallback="setFormCateUuids"
        />
      </basic-form>
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showSelectCol
        showActionCol
        showPagination
        :tableHeight="480"
        :actionColWidth="130"
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :selectionChange="handleSelectionChange"
        :checkSelectable="checkSelectable"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <!-- 按钮操作栏 -->
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <SubmitOrAuditDialog
      :dialogType="submitDialog.type"
      :visible.sync="submitDialog.visible"
      :skuInfo="submitDialog.row"
      :okLoading="submitDialog.loading"
      @getResults="enalbeResults"
    />
    <SubmitOrAuditDialog
      :dialogType="auditDialog.type"
      :visible.sync="auditDialog.visible"
      :skuInfo="auditDialog.row"
      :okLoading="auditDialog.loading"
      @getResults="auditResults"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import SubmitOrAuditDialog from '../components/SubmitOrAuditDialog';
import { AUDIT_PASSED, AUDTI_REJECTED, SUBMIT_TYPE, AUDIT_TYPE } from '../components/constants';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { FORM_ITEMS, TABLE_COLUMNS, SESSION_KEY } from './constants';
import skusPage from '@/mixins/commodity/skusPage';
import { setAuthBtnId } from '@/utils/bizUtils';
import { getInitFormData } from '@/utils/getUtils';
import {
  queryEliminatedGoodsService,
  temporaryNotStopService,
  auditSuccessedService,
  auditFailedService
} from '@/api/stock/eliminatedGoods';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    SubmitOrAuditDialog,
    CategoryMultipleSelect
  },
  data () {
    return {
      formItemList: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false,
        selection: []
      },
      submitDialog: {
        type: SUBMIT_TYPE,
        visible: false,
        loading: false,
        row: {}
      },
      auditDialog: {
        type: AUDIT_TYPE,
        visible: false,
        loading: false,
        row: {}
      }
    }
  },
  mounted () {
    this.runWaitItems();
  },
  computed: {
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    }
  },
  methods: {
    runWaitItems () {
      const { processState } = this.$route.query;
      if (processState) {
        this.formData.processState = processState;
      }
      this.getTableData();
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [{
        label: '批量停用',
        size: 'mini',
        type: 'primary',
        hasAuth: false,
        method: this.handleBatchStop,
        disabled: this.hasNoSelection,
      }];
      return getBtnsBar(h, btnsBar, this.showBtn, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actions = [
        { label: '停用', method: this.handleStop },
        { label: '暂不停用', method: this.handleNotStop, hasAuth: true }
      ]
      const audit = [{ label: '审核', method: this.handleAudit, hasAuth: true }]
      const Maps = {
        'PENDING': actions,
        'AUDIT': audit
      }
      const actionList = Maps[row.processState] ?? [];
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 根据审核状态禁用表格勾选 - 已完成的不可勾选
    checkSelectable ({ row }) {
      return row.processState !== 'OK';
    },
    // 获取查询入参
    getSearchParams () {
      const [createStartTime = '', createEndTime = ''] = this.formData.createTime;
      const formData = _.omit({
        ...this.formData,
        createStartTime,
        createEndTime,
      }, ['createTime']);
      return { ...formData, ...this.paginationParams };
    },
    // 获取表格数据 by 查询表单
    async getTableData () {
      setAuthBtnId('查询');
      const data = this.getSearchParams();
      const loadingFn = state => { this.tableInfo.loading = state };
      const { retData } = await queryEliminatedGoodsService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData.results;
        this.setTotalNum(retData.totalNum);
      }
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 审核
    handleAudit (row) {
      setAuthBtnId('审核');
      this.auditDialog.visible = true;
      this.auditDialog.row = row;
    },
    // 停用
    handleStop (row) {
      this.$router.push({
        name: 'stopOrEnableManageToHandle',
        query: { skuNo: row.skuNo }
      });
    },
    // 暂不停用
    handleNotStop (row) {
      setAuthBtnId('暂不停用');
      this.submitDialog.visible = true;
      this.submitDialog.row = row;
    },
    // 批量停用
    handleBatchStop () {
      const skuNos = this.tableInfo.selection.map(item => item.skuNo);
      sessionStorage.setItem(SESSION_KEY, JSON.stringify(skuNos));
      this.$router.push({
        name: 'stopOrEnableManageToHandle',
        query: { cacheKey: SESSION_KEY }
      });
    },
    // 暂不停用结果
    async enalbeResults (note) {
      const loadingFn = state => { this.submitDialog.loading = state };
      const data = {
        uuid: this.submitDialog.row.uuid,
        submitReason: note
      }
      const res = await temporaryNotStopService(data, loadingFn)
      if (res) {
        this.$message.success('暂不停用成功');
        this.submitDialog.visible = false;
        this.getTableData();
      }
    },
    // 审核结果
    async auditResults (note, type) {
      const Maps = {
        [AUDIT_PASSED]: { msg: '审核通过', method: auditSuccessedService },
        [AUDTI_REJECTED]: { msg: '审核不通过', method: auditFailedService }
      }
      const loadingFn = state => { this.auditDialog.loading = state };
      const data = {
        uuid: this.auditDialog.row.uuid,
        auditDesc: note
      }
      const { msg, method } = Maps[type];
      const res = await method(data, loadingFn)
      if (res) {
        this.$message.success(`${msg}成功`);
        this.auditDialog.visible = false;
        this.getTableData();
      }
    },
    // 获取关联品类信息
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    // 清空品类选择信息
    clearCategorySelect () {
      this.$refs.categoryMultiple.clearSelectResult()
    },
  }
}
</script>
